//
//  ST_HeroHomepageController.swift
//  btvideo
//
//  Created by Jason on 2021/11/12.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import HandyJSON
import SwiftyJSON
import SnapKit
import SwiftyUserDefaults
import NIMSDK
import MJRefresh
import SwiftyAttributes

//其他人个人主页-Controller 弃用
class ST_HeroHomepageController: UIViewController {
    
    let accid:String
    
    let heroAlbum:[ST_PairsShareParticularModel]
    
    var header_height:CGFloat
    
    init(accid:String,heroAlbum:[ST_PairsShareParticularModel]){
        
        self.accid = accid
        self.heroAlbum = heroAlbum
        
        if let first = heroAlbum.first{
            
            self.header_height = first.displayHeight + 50
            
        }else{
            
            self.header_height = 375
        }
        
        super.init(nibName: nil, bundle: nil)
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    deinit {
        
        NotificationCenter.default.removeObserver(self)
        
        print("内存释放问题----1")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = Color.clear
        
        let bottomEdge : CGFloat = iPhoneXSeries ? 0 : -30
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: statusBarHeight, left: 0, bottom: bottomEdge, right: 0))
        }
        tableView.cornerRadius = 30
        
        view.addSubview(back_btn)
        back_btn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(statusBarHeight+7)
            make.width.height.equalTo(30)
        }
        
        headerHeight_modified()
        
        fetch_remote_data_set()
        
        
        
        if accid == Defaults[.currentUserID]{
            
            view.addSubview(edit_my_info_btn)
            edit_my_info_btn.snp.makeConstraints { (make) in
                make.width.equalTo(260)
                make.height.equalTo(40)
                make.bottom.equalToSuperview().offset(-BTSafeAreaBottom-10)
                make.centerX.equalToSuperview()
            }
            
            NotificationCenter.default.addObserver(self, selector: #selector(fetch_remote_data_set), name: Notification.Name.push_peculiarity_success, object: nil)
            
            NotificationCenter.default.addObserver(self, selector: #selector(fetch_remote_data_set), name: Notification.Name.my_pairs_user_info_updated, object: nil)
            
            NotificationCenter.default.addObserver(self, selector: #selector(fetch_remote_data_set), name: Notification.Name.like_peculiarity, object: nil)
            
            NotificationCenter.default.addObserver(self, selector: #selector(fetch_remote_data_set), name: Notification.Name.approved_peculiarity, object: nil)
            
            return
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(refresh_love_botton), name: Notification.Name.pairs_prop_updated, object: nil)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(refresh_header_guide(nofi:)), name: Notification.Name.sendGuard, object: nil)
        
        
        Defaults[.lookOtherPerson] = Defaults[.lookOtherPerson] + 1
        
        fetch_user_survey_data()
        
        view.addSubview(more_action_btn)
        more_action_btn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15)
            make.top.equalToSuperview().offset(statusBarHeight+7)
            make.width.height.equalTo(30)
        }
        
        self.footerView.modify_height_closure = {[weak self] height in
            
            self?.footerView.frame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: ScreenWidth, height: height))
            
            self?.tableView.tableFooterView = self?.footerView
        }
        
    }
    
    func operate_after_handle(){
        
        self.layout_operation_btns()
        
        //        self.back_handle()
    }
    
    @objc func refresh_header_guide(nofi:Notification){
        
        let json = JSON(nofi.userInfo ?? "")
        
        
        if json["userId"].stringValue != self.viewModel.tableHeaderViewModel.accid{
            return
        }
        
        let str = self.viewModel.tableHeaderViewModel.guideModel?.herAvatar ?? ""
        
        let gModel = PairsGuardModel.create_present_finish_model(notificationJson: json, avatar: str)
        
        self.viewModel.tableHeaderViewModel.isMyGuard = true
        
        self.viewModel.tableHeaderViewModel.guideModel = gModel
        
        self.headerView.model?.guideModel = gModel
        
        self.headerView.refresh_guide_view()
        
    }
    
    @objc func refresh_love_botton(){
        
        if self.viewModel.is_friends{
            
            gift_btn.alpha = 1
            like_btn.alpha = 0
            magic_btn.alpha = 0
            
        }else if self.viewModel.tableHeaderViewModel.is_attention{
            
            magic_btn.alpha = 0
            gift_btn.alpha = 1
            like_btn.alpha = 0
//            gift_btn.alpha = 0
            
        }else{
            
            like_btn.alpha = 1
            magic_btn.alpha = 0
            gift_btn.alpha = 0
        }
        
    }
    
    func layout_operation_btns(){
        
        if self.accid == Defaults[.currentUserID]{
            return
        }
        
        view.addSubview(bottom_button_effect_view)
        bottom_button_effect_view.snp.makeConstraints { (make) in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(174-34+BTSafeAreaBottom)
        }
        
//        默认或者忙碌展示 搭讪UI
        if viewModel.liveBeautyStatue == 0 || viewModel.liveBeautyStatue == 3{
            
            view.addSubview(accost_btn)
            accost_btn.snp.makeConstraints { (make) in
                make.bottom.equalTo(bottom_button_effect_view).offset(-10-BTSafeAreaBottom)
                make.height.equalTo(44)
                make.width.equalTo(TIANCompatibleValue(value: 237))
                make.left.equalToSuperview().offset(15)
            }
            
            view.addSubview(magic_btn)
            magic_btn.snp.makeConstraints { (make) in
                make.right.equalToSuperview().offset(-12)
                make.width.equalTo(50)
                make.height.centerY.equalTo(accost_btn)
            }
            
            view.addSubview(like_btn)
            like_btn.snp.makeConstraints { (make) in
                make.edges.equalTo(magic_btn)
            }
            
            view.addSubview(gift_btn)
            gift_btn.snp.makeConstraints { (make) in
                make.edges.equalTo(magic_btn)
            }
            
            view.addSubview(chat_btn)
            chat_btn.snp.makeConstraints { (make) in
                make.height.centerY.width.equalTo(magic_btn)
                make.right.equalTo(magic_btn.snp.left).offset(0)
            }
            
        }else{
            
            
            view.addSubview(live_talk_btn)
            live_talk_btn.snp.makeConstraints { (make) in
                make.bottom.equalTo(bottom_button_effect_view).offset(-10-BTSafeAreaBottom)
                make.height.equalTo(44)
                make.width.equalTo(TIANCompatibleValue(value: 237))
                make.right.equalToSuperview().offset(-20)
            }
//            视频
            if viewModel.liveBeautyStatue == 2{
                
                live_talk_btn.setBackgroundImage(UIImage.init(color: live_talk_video_background_color, size: CGSize.init(width: 1, height: 1)), for: UIControl.State.normal)
                
                live_talk_btn.setTitleForAllStates(" 与TA视频聊天")
                live_talk_btn.setImageForAllStates(live_talk_video_icon)
            }
//            语音
            else if viewModel.liveBeautyStatue == 1{
                
                live_talk_btn.setBackgroundImage(UIImage.init(color: liveTalkVoiceBackgroundColor, size: CGSize.init(width: 1, height: 1)), for: UIControl.State.normal)
                
                live_talk_btn.setTitleForAllStates(" 与TA语音聊天")
                
                live_talk_btn.setImageForAllStates(live_talk_voice_icon)
            }
            
            
            view.addSubview(magic_btn)
            magic_btn.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(12)
                make.width.equalTo(50)
                make.height.centerY.equalTo(live_talk_btn)
            }
            
            view.addSubview(like_btn)
            like_btn.snp.makeConstraints { (make) in
                make.edges.equalTo(magic_btn)
            }
            
            view.addSubview(gift_btn)
            gift_btn.snp.makeConstraints { (make) in
                make.edges.equalTo(magic_btn)
            }
            
            view.addSubview(chat_btn)
            chat_btn.snp.makeConstraints { (make) in
                make.height.centerY.width.equalTo(magic_btn)
                make.left.equalTo(magic_btn.snp.right).offset(0)
            }
            
        }
        
        
        
        refresh_love_botton()
        
    }
    
    
    
    
    
    
    
//    func package_header_play_view(_ view:ST_PairsShareParticularView){
//
//
//        view.cornerRadius = 0
//
//        self.headerView.package_play_view(view)
//
//    }
//
    
    
    //    MARK: - Data Array
    
    lazy var viewModel:ST_PairsUserCenterViewModel = {
        
        let m = ST_PairsUserCenterViewModel()
        m.tableHeaderViewModel.accid = self.accid
        return m
    }()
    
    
    
    /**
     收到的喜欢
     */
    var love_square_operation = false
    
    var sendWay = ST_LoveWay.recommend
    /**
     特质id 如需要 请传递
     */
    var peculiarity_id = ""
    
    
    
    //    MARK: - properties
    fileprivate lazy var back_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("详情_icon_返回")!)
        control.addTarget(self, action: #selector(back_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var more_action_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("详情_icon_更多操作")!)
        control.addTarget(self, action: #selector(actions_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var bottom_button_effect_view:ST_FWGradientView = {
       let control = ST_FWGradientView()
        control.isUserInteractionEnabled = false
        
        if iPhoneXSeries{
            control.model = ST_FWGradientViewModel.init(locations: [0,0.7,1], colors: [UIColor.init(white: 1, alpha: 0),UIColor.init(white: 1, alpha: 0.85),UIColor.init(white: 1, alpha: 1)], startPoint: CGPoint.init(x: 0, y: 0), endPoint: CGPoint.init(x: 0, y: 1))
        }else{
            control.model = ST_FWGradientViewModel.init(locations: [0,0.7,1], colors: [UIColor.init(white: 1, alpha: 0),UIColor.init(white: 1, alpha: 0.85),UIColor.init(white: 1, alpha: 1)], startPoint: CGPoint.init(x: 0, y: 0), endPoint: CGPoint.init(x: 0, y: 1))
        }
        
        return control
    }()
    
    fileprivate lazy var accost_btn:UIControl = {
        let control = UIControl()
        
        let gradientBackView = ST_FWGradientView()
        gradientBackView.isUserInteractionEnabled = false
        gradientBackView.model = ST_FWGradientViewModel.init(locations: [0,1], colors: [UIColor.init(hex: 0xFFDE11)!,UIColor.init(hex: 0xF8BC00)!], startPoint: CGPoint.init(x: 0, y: 0), endPoint: CGPoint.init(x: 0, y: 1))
        control.addSubview(gradientBackView)
        gradientBackView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        let imgView = UIImageView()
        imgView.image = ST_ImageUtils.imageName("accost189232")
        control.addSubview(imgView)
        imgView.snp.makeConstraints { (make) in
            make.width.height.equalTo(24)
            make.centerY.equalToSuperview()
            make.centerX.equalToSuperview().offset(-12-5)
        }
        
        
        let label = UILabel()
        control.addSubview(label)
        label.text = "搭讪"
        label.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        label.textColor = .white
        label.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.centerX.equalToSuperview().offset(12+5)
        }
        
        control.cornerRadius = 22
        
        control.addTarget(self, action: #selector(accost_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var live_talk_video_background_color = UIColor.init(hex: 0xFEC207)!
    
    fileprivate lazy var liveTalkVoiceBackgroundColor = UIColor.init(hex: 0x54E78E)!
    
    fileprivate lazy var live_talk_voice_icon = ST_ImageUtils.imageName("pairs_center_liveTalk_voice_Action_icon")!
    
    fileprivate lazy var live_talk_video_icon = ST_ImageUtils.imageName("pairs_center_liveTalk_video_Action_icon")!
  
    fileprivate lazy var live_talk_btn:UIButton = {
        
        let control = UIButton()
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        control.setTitleColorForAllStates(UIColor.white)
        control.cornerRadius = 22
        control.addTarget(self, action: #selector(invite_chat_action), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    lazy var another_like_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("个人中心_center_icon")!)
        control.addTarget(self, action: #selector(send_like_handle(sender:)), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    lazy var chat_btn:ST_VerticalButton = {
        let control = ST_VerticalButton()
        control.setImageForAllStates(ST_ImageUtils.imageName("chatcopy034034")!)
        control.setTitleForAllStates("私聊".withAttributes([Attribute.font(UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)),.textColor(UIColor.init(hex: 0x333333)!)]))
        control.title_bottom_offset = 0
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 13, bottom: 20, right: 13)
        control.addTarget(self, action: #selector(chat_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    lazy var like_btn:ST_VerticalButton = {
        let control = ST_VerticalButton()
        control.setImageForAllStates(ST_ImageUtils.imageName("likeGold")!)
        control.setTitleForAllStates("喜欢".withAttributes([Attribute.font(UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)),.textColor(UIColor.init(hex: 0x333333)!)]))
        control.title_bottom_offset = 0
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 13, bottom: 20, right: 13)
        control.addTarget(self, action: #selector(send_like_handle(sender:)), for: UIControl.Event.touchUpInside)
        control.alpha = 0
        return control
    }()
    
    lazy var gift_btn:ST_VerticalButton = {
        let control = ST_VerticalButton()
        control.setImageForAllStates(ST_ImageUtils.imageName("chat_gift_icon")!)
        control.setTitleForAllStates("礼物".withAttributes([Attribute.font(UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)),.textColor(UIColor.init(hex: 0x333333)!)]))
        control.title_bottom_offset = 0
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 13, bottom: 20, right: 13)
        control.addTarget(self, action: #selector(show_goods_handle), for: UIControl.Event.touchUpInside)
        control.alpha = 0
        return control
    }()
    
    
    lazy var magic_btn:ST_VerticalButton = {
        let control = ST_VerticalButton()
        control.setImageForAllStates(ST_ImageUtils.imageName("magicGold")!)
        control.setTitleForAllStates("立即匹配".withAttributes([Attribute.font(UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)),.textColor(UIColor.init(hex: 0x333333)!)]))
        control.title_bottom_offset = 0
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 13, bottom: 20, right: 13)
        control.addTarget(self, action: #selector(open_magic_tools_handle(sender:)), for: UIControl.Event.touchUpInside)
        control.alpha = 0
        return control
    }()
    
    lazy var ignore_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("矩形000019")!)
        control.addTarget(self, action: #selector(unlike_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    
    
    /**
     首页跳转 需要不喜欢按钮
     */
    var home_pushed = false
    
    /**
     收到的喜欢界面跳转过来
     */
    var from_receive_love = false
    
   
    
    fileprivate lazy var props_guide_view = ST_PairsCenterPropsGuideView()
    
    
    fileprivate lazy var props_exchange_view:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("pairsPropExchangeIcon")!)
              return control
          }()
    
    
    fileprivate lazy var edit_my_info_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("编辑资料")
        control.setTitleColor(UIColor.white, for: UIControl.State.selected)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        control.cornerRadius = 20
        control.backgroundColor = Color.init(hexString: "#FEC207")
        control.addTarget(self, action: #selector(edit_my_info_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    lazy var tableView:UITableView = {
        
        let control = UITableView.init(frame: CGRect.zero, style: UITableView.Style.grouped)
        
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom + 50 , right: 0)
        
        control.delegate = self
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        control.dataSource = self
        
        control.register(cellWithClass: UITableViewCell.self)
        control.register(cellWithClass: ST_PairsCenterDailyCell.self)
        control.register(cellWithClass: ST_PairsCenterPeculiaritySingleDetailCell.self)
        control.register(cellWithClass: ST_PairsCenterPeculiarityDoubleDetailCell.self)
        control.register(cellWithClass: ST_PairsCenterPeculiarityThreeDetailCell.self)
        control.register(cellWithClass: ST_PairsCenterPeculiarityQuartDetailCell.self)
        control.register(cellWithClass: PairsCenterSubTitleCell.self)
        
        control.register(cellWithClass: ST_PairsLoveMultiST_PeculiarityCell.self)
        control.register(cellWithClass: PairsMyLoveMultiST_PeculiarityCell.self)
        
        
        control.register(cellWithClass: ST_PairsCenterTextMapCell.self)
        control.register(cellWithClass: ST_PairsCenterTextCell.self)
        control.register(cellWithClass: ST_PairsCenterPeculiaritySectionCell.self)
        
        
        //        新增
        control.register(cellWithClass: ST_PairsCenterOnlyMyLovePecCell.self)
        control.register(cellWithClass: ST_PairsCenterMatchPecCell.self)
        control.register(cellWithClass: ST_PairsCenterOnlyLoveMePecCell.self)
        
        //        加载中
        
        
        control.register(cellWithClass: ST_PairsCenterMatchloadingCell.self)
        
        control.register(headerFooterViewClassWith: ST_PairsCenterCornerSectionHeaderView.self)
        control.register(headerFooterViewClassWith: ST_PairsCenterCornerSectionFooterView.self)
        
        control.register(headerFooterViewClassWith: PairsDailySectionFooterView.self)
        
        
        control.separatorStyle = .none
        
        control.backgroundColor = Color.init(hex: 0xACB4C0)
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        
        control.tableHeaderView = self.headerView
        control.tableFooterView = self.footerView
        
        return control
    }()
    
    //    MARK: - header Properties
    
    
    lazy var headerView:ST_PairsCenterHeaderView = {
        
        let control = ST_PairsCenterHeaderView(frame: CGRect.init(x: 0, y: 0, width: ScreenWidth, height: header_height))
        
        control.phDelegate = self
        
        control.create_play_view()
        
        let model = ST_PairsMyCenterHeaderViewModel()
        
        model.particularArray = heroAlbum
        
        control.bind_model(model)
        
        return control
    }()
    
    fileprivate lazy var footerView:ST_PairsCenterFooterView = {
        
        let control = ST_PairsCenterFooterView(frame: CGRect.init(x: 0, y: 0, width: ScreenWidth, height: 0))
        //        control.isHidden = true
        return control
    }()
    
    
    
    
    private func headerHeight_modified(){
        
        self.headerView.frame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: ScreenWidth, height: header_height))
        
        let pairsheaderHeight = header_height - self.viewModel.tableHeaderViewModel.headerExtensionHeight
        
        self.headerView.pairsHeader?.frame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: ScreenWidth, height: pairsheaderHeight))
        
        self.tableView.tableHeaderView = self.headerView
    }
    
}

extension ST_HeroHomepageController{
    
    fileprivate func fetch_user_survey_data(){
        
        if ST_BTUserInfoManager.shared.additional_attributes?.needSurvey == false{
            return
        }
        
        if Defaults[.lookOtherPerson] == 5 || Defaults[.lookOtherPerson] == 10{
            
            JVrequest(PH.fetchSurveyBaseDataApi, success: { (childJson) in
                
                print("调研问题：",childJson)
                
                if let survey = ST_SurveyModel.deserialize(from: childJson["data"][0].rawString() ?? "") {
                    
                    let vc = ST_SurveyViewController_AIVersion()
                    
                    vc.model = survey
                    
                    vc.overCurrentContext = true
                    
                    GlobalPresent(toController: vc)
                    
                }
                
            }) { (code, err) in
                
            }
        }
        
    }
    
    @objc func fetch_remote_data_set() {
        
        
        print("个人主页接口开始",Date())
        
        JVrequest(PH.otherPeopleNewInfoApi,parameters: ["target_accid":accid],success: { (json) in
        
            
            print("个人主页接口结束",Date(),json)
            
            
            self.viewModel = ST_PairsUserCenterViewModel.deserialize(from: json["data"], accid: self.accid)

            
//                        待开发
            //非交互跳转 使用接口数据
//            let albums = ST_PairsShareParticularModel.describe(json_array: json["data"]["album"].arrayValue)
            

//            self.viewModel.tableHeaderViewModel.particularArray = albums
//
//            self.viewModel.tableHeaderViewModel.setUpViewDataSet()
            
//            if let first = self.viewModel.tableHeaderViewModel.particularArray.first{
//
//                self.header_height = first.displayHeight + self.viewModel.tableHeaderViewModel.headerExtensionHeight
//
//            }
            
            
//            self.viewModel.tableHeaderViewModel.accid = self.accid
            
//            待开发
//            self.headerView.bind_model(self.viewModel.tableHeaderViewModel)
            
            self.tableView.reloadData {
                
                self.tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
                    
                    self?.request_recommend_data()
                })
                
                self.request_match_data()
            }
            
            
            
            
            self.like_btn.isSelected = self.viewModel.tableHeaderViewModel.is_attention
            
            self.layout_operation_btns()
            
            
            
        }) { (code, error) in
            print("当前错误❌:",error)
        }
        
    }
    
    func request_match_data(){
        
       
        
        JVrequest(PH.RecommendPersonAppendDataApi,parameters: ["target_accid":accid], success: { (json) in
            
            self.viewModel.appendMatch(json: json["data"])
            
            self.tableView.reloadData()
            
        }) { (code, err) in
            
        }
        
    }
    
    
    
    /**请求 推荐数据*/
    func request_recommend_data(){
        
        JVrequest(PH.RecommendPersonApi,parameters: ["target_accid":accid], success: { (json) in
            
            print("个人主页推荐 ：",json)
            
            var recommend_array = [ST_PinterestHomeCellModel]()
            
            for item in json["data"].arrayValue{
                
                let model = ST_PinterestHomeCellModel.init(recommendJson: item)
                
                recommend_array.append(model)
            }
            
            self.footerView.data_array = recommend_array
            
            self.tableView.mj_footer = nil
            
            //            self.footerView.isHidden = false
            //            self.tableView.reloadData()
            
        }) { (code, err) in
            
            ToastHud(text: err, view: self.view)
        }
        
    }
    
}
//MARK: - Event
extension ST_HeroHomepageController{
   
    @objc func invite_chat_action(){
        
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self) {
            return
        }
        
        var isVideo:Bool?
        if viewModel.liveBeautyStatue == 2{
            isVideo = true
        }else if viewModel.liveBeautyStatue == 1{
            isVideo = false
        }
        
        guard let v = isVideo else { return  }
        
        
        
        live_talk_btn.isUserInteractionEnabled = false
        
        main_thread_execute(afterDelay: 1) {
            
            self.live_talk_btn.isUserInteractionEnabled = true
        }
        
        
        
        if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == viewModel.tableHeaderViewModel.sex,let str = SCComponets.rich_text_storage_component.json["limitations"]["cot"].string,str.count > 2{
            
            self.toast(text: str)
            
            return
        }
        
        
        ST_MediaChatDispatcher.shared.inviteChat(sessionId: accid, isVideo: v,inviteDistract: "upLiveWall")
        
    }
    
    @objc func back_handle(){
        
        headerView.isUserInteractionEnabled = false
        
        
        
        guard let nav = self.navigationController, let first = nav.viewControllers.first,first is ST_HeroHomepageController && first != self else {
            
            goback_previous_controller()
            
            return
        }
        
        nav.transitioningDelegate = nil
        
        nav.dismiss(animated: true) {
            
        }
        
        
    }
    @objc func unlike_handle(){
        
        
        
        guard let album = self.headerView.pairsHeader?.data_array.first else{
            return
        }
        
        
        self.ignore_btn.isUserInteractionEnabled = false
        
        let info = ST_MatchUserInfo(accid: self.accid, avatar: album.imageUrl, nickname: self.viewModel.tableHeaderViewModel.nickname)
        
        PairsLikeAction(info: info, likeAction: false, isReceive: from_receive_love, fromVC: self) { (code, err , matched) in
            
            self.ignore_btn.isUserInteractionEnabled = true
            
            
            if code == 1{
                
                matched?()
                
                self.viewModel.tableHeaderViewModel.is_attention = false
                
                self.ignore_next_step()
                
            }else {
                
                if let e = err{ self.toast(text: e) }
                
            }
            /*
             if let e = err{
             
             self.toast(text: e)
             
             }else{
             
             self.viewModel.tableHeaderViewModel.is_attention = false
             
             self.ignore_next_step()
             }*/
        }
        
        
    }
    
    @objc func ignore_next_step(){
        
        
        self.layout_operation_btns()
        
        self.headerView.isUserInteractionEnabled = false
        
        
        self.goback_previous_controller(animated: true) {
            
            NotificationCenter.default.post(name: Notification.Name.ignore_somebody, object: nil, userInfo: ["accid": self.accid])
        }
    }
    
    @objc fileprivate func open_magic_tools_handle(sender:UIControl){
        
      
        let vc = ST_SendAirshipViewController()
        
        vc.overCurrentContext = true
     
        vc.send_closure = {[weak self] m in
            self?.send_air_ship(model: m)
        }
        
        GlobalPresent(toController: vc)
        
    }
    
    
    @objc func show_goods_handle(){
        
        let giftAlert = ST_GiftViewController()
        
        giftAlert.overCurrentContext = true
        
        giftAlert.over_current_context_alpha = "0.4"
        
        giftAlert.userId = self.accid
        
        if let user = BINP.fetch_nickname_with_avatar(userId: self.accid){
        
            giftAlert.avatar = user.avatar
        }
        
        
        GlobalPresent(toController: giftAlert)
        
    }
    
    @objc fileprivate func send_like_handle(sender:UIControl){
     
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self) {
            return
        }
        
        push_to_remote_like_action(id: nil)
        
    }
    
    fileprivate func send_air_ship(model:ST_ChooseAirshipCellModel){
        
        
        let vc = ST_PairsPropBrowserController()
                    
        vc.overCurrentContext = true
        
        vc.animationIndex = model.id
        
        vc.play_completion_closure = { [weak self] in
            
            self?.push_to_remote_like_action(id: model.id.string)
            
        }
        
        GlobalPresent(toController: vc, animated: false)
        
    }
    
    
    fileprivate func push_to_remote_like_action(id:String? = nil){
        
        
        guard let album = self.headerView.pairsHeader?.data_array.first else{
            return
        }
        
        
        self.like_btn.isUserInteractionEnabled = false
        
        let info = ST_MatchUserInfo(accid: self.accid, avatar: album.imageUrl, nickname: self.viewModel.tableHeaderViewModel.nickname)
        
        PairsLikeAction(info: info, likeAction: true, isReceive: self.from_receive_love, fromVC: self,propId:id) { (code, err , matched) in
            
            self.like_btn.isUserInteractionEnabled = true
            
            
            if code == 1{
                
                matched?()
                
                self.viewModel.tableHeaderViewModel.is_attention = true
          
                self.operate_after_handle()
                
            }else {
                
                if let e = err{ self.toast(text: e) }
                
            }
        
        }
        
        
    }
    
    
    
    @objc func ban_current_user_handle(){
        
        BAN_SOMEBODY_HANDLE(userId: self.accid, close_view: true, hud_controller: self)
        
    }
    
    /**
     屏蔽点击事件
     */
    func shield_click_on_loading(isShield:Bool){
        
        self.footerView.isUserInteractionEnabled = !isShield
        
        self.headerView.isUserInteractionEnabled = !isShield
        
        self.tableView.visibleCells.forEach { (itemCell) in
            itemCell.isUserInteractionEnabled = !isShield
        }
        
    }
    
    @objc func accost_handle(){
        
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self) {
            return
        }
        
        ST_TianAccostManager.shared.accost(idSet: [self.accid], viewController: self) { (json) in
            
            self.toast(text: "搭讪成功")
        }
    }
    
    @objc func chat_handle(){
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self) {
            return
        }
        
        
        if let avatar = viewModel.tableHeaderViewModel.particularArray.first?.imageUrl{
            
            BINP.update_base_info(remoteInfo: ST_BTUserInfoFromRemote.init(accid: accid, avatar: avatar, userName: viewModel.tableHeaderViewModel.nickname))
        }
        
        ST_BTBootController.shared.presentChatController(sessionId: accid, chatTitle: viewModel.tableHeaderViewModel.nickname)
        
    }
    
    @objc func edit_my_info_handle(){
        
        let editVC = ST_EditMyInfoViewController()
        
        self.navigationController?.pushViewController(editVC, animated: true)
        
    }
    
    
    
    
    
    @objc func actions_handle(){
        
        let vc = ST_BTSheetActionController.init(title: nil, message: nil)
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
        
        
        var actionStr:String?
        //        好友 解除匹配
        if self.viewModel.is_friends{
            
            actionStr = "解除匹配"
            
        }
        //      不感兴趣,没有喜欢过
        else if self.viewModel.tableHeaderViewModel.is_attention == false{
            
            actionStr = "不感兴趣"
        }
        
        if let aStr = actionStr {
            
            
            let str1 = NSMutableAttributedString.init(string: aStr)
            
            str1.addAttributes(attr, range: NSRange(location: 0, length: str1.length))
            
            vc.addAction(ST_BTAlertAction.init(title: str1, handler: {[weak self] (action) in
                
                guard let strongSelf = self else{
                    return
                }
                
                //                解除匹配
                if strongSelf.viewModel.is_friends{
                    
                    JVrequest(PH.removeMatchApi, parameters: ["target_accid":strongSelf.viewModel.tableHeaderViewModel.accid],success: { (json) in
                        
                        ST_ConversationAdapter.shared.delete_recent_conversation(sessionId: strongSelf.viewModel.tableHeaderViewModel.accid)
                        
                        ST_BTUserInfoManager.shared.refresh_my_sweetheart_list()
                        
                        
                        self?.back_handle()
                        
                    },failure: { (code, err) in
                        
                        self?.toast(text: err)
                    })
                }
                //      不感兴趣,没有喜欢过
                else if strongSelf.viewModel.tableHeaderViewModel.is_attention == false{
                    
                    strongSelf.unlike_handle()
                }
                
            }))
            
            
            
            
            
        }
        
        
        let str2 = NSMutableAttributedString.init(string: "拉黑")
        
        str2.addAttributes(attr, range: NSRange(location: 0, length: str2.length))
        
        vc.addAction(ST_BTAlertAction.init(title: str2, handler: {[weak self] (action) in
            
            guard let strongSelf = self else{return}
            
            strongSelf.ban_current_user_handle()
        }))
        
        
        let str3 = NSMutableAttributedString.init(string: "举报")
        
        str3.addAttributes(attr, range: NSRange(location: 0, length: str3.length))
        
        vc.addAction(ST_BTAlertAction.init(title: str3, handler: {[weak self] (action) in
            
            
            guard let strongSelf = self else{return}
            
            let vc = ST_ReportPersonController()
            vc.userId = strongSelf.accid
            let nav = UINavigationController.create_hiding_bar_navigation_controller(rootViewController: vc)
            GlobalPresent(toController: nav)
            
        }))
        
        vc.show()
        
        
        
    }
    
    
}


//MARK: - UITableViewDelegate
extension ST_HeroHomepageController:UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int{
        return viewModel.datasets.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.datasets[safe:section]?.list.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        if let iCell = cell as? ST_PairsCenterMatchloadingCell{
            iCell.stopAnimating()
        }
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        if let iCell = cell as? ST_PairsCenterMatchloadingCell{
            iCell.startAnimating()
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if let model = viewModel.datasets[safe:indexPath.section]?.list[safe:indexPath.row]{
            
            switch model.cellType {
            case .subTitle:
                
                let cell = tableView.dequeueReusableCell(withClass: PairsCenterSubTitleCell.self, for: indexPath)
                
                if let cellModel = model as? ST_PairsInfoModel{
                    cell.model = cellModel
                }
                return cell
            case .textMap:
                
                let cell = tableView.dequeueReusableCell(withClass: ST_PairsCenterTextMapCell.self, for: indexPath)
                
                if let cellModel = model as? ST_PairsInfoModel{
                    cell.model = cellModel
                }
                
                return cell
                
            case .peculiaritySection,.onlyLikePeculiarityExcludeMe:
                
                let cellModel = model as! ST_PairsLovePeculiaritySetsModel
                
                if cellModel.ta == "我"{
                    
                    let cell = tableView.dequeueReusableCell(withClass: PairsMyLoveMultiST_PeculiarityCell.self, for: indexPath)
                    
                    cell.model = cellModel
                    
                    return cell
                    
                }else{
                    
                    let cell = tableView.dequeueReusableCell(withClass: ST_PairsLoveMultiST_PeculiarityCell.self, for: indexPath)
                    
                    cell.model = cellModel
                    
                    return cell
                }
                
            case .peculiarityDetail:
                
                if let cellModel = model as? ST_PairsPeculiarity{
                    
                    if cellModel.detail.count >= 4{
                        
                        let cell = tableView.dequeueReusableCell(withClass: ST_PairsCenterPeculiarityQuartDetailCell.self, for: indexPath)
                        
                        cell.model = cellModel
                        
                        return cell
                    }else if cellModel.detail.count == 3{
                        
                        let cell = tableView.dequeueReusableCell(withClass: ST_PairsCenterPeculiarityThreeDetailCell.self, for: indexPath)
                        
                        cell.model = cellModel
                        
                        return cell
                    }else if cellModel.detail.count == 2{
                        
                        let cell = tableView.dequeueReusableCell(withClass: ST_PairsCenterPeculiarityDoubleDetailCell.self, for: indexPath)
                        
                        cell.model = cellModel
                        
                        return cell
                    }else{
                        
                        let cell = tableView.dequeueReusableCell(withClass: ST_PairsCenterPeculiaritySingleDetailCell.self, for: indexPath)
                        
                        cell.model = cellModel
                        
                        return cell
                    }
                }
                break
            case .daily:
                
                let cell = tableView.dequeueReusableCell(withClass: ST_PairsCenterDailyCell.self, for: indexPath)
                
                if let cellModel = model as? ST_PairsOwnDailySetsModel{
                    cell.model = cellModel
                }
                
                return cell
                
            case .peculiarityMatch:
                
                let cell = tableView.dequeueReusableCell(withClass: ST_PairsCenterMatchPecCell.self, for: indexPath)
                
                if let cellModel = model as? ST_PairsCenterMatchPecCellModel{
                    cell.model = cellModel
                }
                
                return cell
                
            case .onlyMyLovePeculiarity:
                
                let cell = tableView.dequeueReusableCell(withClass: ST_PairsCenterOnlyMyLovePecCell.self, for: indexPath)
                
                if let cellModel = model as? ST_PairsCenterOnlyMyLovePecCellModel{
                    cell.model = cellModel
                }
                
                return cell
                
            case .onlyLoveMePeculiarity:
                
                let cell = tableView.dequeueReusableCell(withClass: ST_PairsCenterOnlyLoveMePecCell.self, for: indexPath)
                
                if let cellModel = model as? ST_PairsCenterOnlyLoveMePecCellModel{
                    cell.model = cellModel
                }
                
                return cell
            case .loading:
                
                let cell = tableView.dequeueReusableCell(withClass: ST_PairsCenterMatchloadingCell.self, for: indexPath)
                
                return cell
            default:
                let cell = tableView.dequeueReusableCell(withClass: ST_PairsCenterTextCell.self, for: indexPath)
                
                if let cellModel = model as? ST_PairsInfoModel{
                    cell.model = cellModel
                }
                return cell
            }
        }
        
        return tableView.dequeueReusableCell(withClass: UITableViewCell.self, for: indexPath)
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        guard let height = viewModel.datasets[safe:indexPath.section]?.list[safe:indexPath.row]?.pairsCellHeight else { return 60 }
        
        return height
    }
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        guard let model = viewModel.datasets[safe:section] else { return nil }
        
        
        if !model.displayHeader{
            return nil
        }
        
        let header = tableView.dequeueReusableHeaderFooterView(withClass: ST_PairsCenterCornerSectionHeaderView.self)
        
        header.model = model.head
        
        return header
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        guard let model = viewModel.datasets[safe:section] else { return 0 }
        
        
        if !model.displayHeader{
            return 0
        }
        
        return model.head.sectionHeight
        
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        guard let model = viewModel.datasets[safe:section] else { return nil }
        
        if !model.displayFooter{
            return nil
        }
        
        if model.head.text.contains("日常"){
            
            let footer = tableView.dequeueReusableHeaderFooterView(withClass: PairsDailySectionFooterView.self)
            
            footer.model = model.footer
            
            footer.moreDataClosure = {[weak self] in
                self?.pushHerDailyHandle()
            }
            
            return footer
            
        }else{
            let footer = tableView.dequeueReusableHeaderFooterView(withClass: ST_PairsCenterCornerSectionFooterView.self)
            
            footer.model = model.footer
            
            return footer
        }
        
        
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        
        guard let model = viewModel.datasets[safe:section] else { return 0 }
        
        if !model.displayFooter{
            return 0
        }
        
        return model.footer.sectionHeight
    }
    
    //    MARK: tableView click Event
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        
        if let model = viewModel.datasets[safe:indexPath.section]?.list[safe:indexPath.row] {
            
            switch model.cellType {
            case .daily:
                
                pushHerDailyHandle()
                
                break
            case .textMap:
                break
                
            case .peculiaritySection:
                break
                
            case .peculiarityDetail:
                
                guard let pairsModel = model as? ST_PairsPeculiarity else{
                    return
                }
                
                let vc = ST_SinglePeculiarityWaterfallController()
                vc.userID = self.accid
                vc.peculiarity_id = pairsModel.id.string
                
                
                if Defaults[.currentUserID] == self.accid{
                    
                    vc.type = .me
                    
                }else{
                    vc.type = .normal
                }
                
                navigationController?.pushViewController(vc)
                
                
                break
            default:
                break
            }
        }
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        
        
    }
    
    fileprivate func pushHerDailyHandle(){
        
        let vc = ST_PersonalDailyViewController()
        
        vc.title = viewModel.ta + "的日常"
        
        vc.userId = self.accid
        
        navigationController?.pushViewController(vc)
        
    }
}



//MARK: - Pairs Header Delegate

extension ST_HeroHomepageController:ST_PairsShareParticularViewDelegate{
    
    func PHScrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
    }
    
    
    func PHScrollViewDidScroll(_ scrollView: UIScrollView, viewHeight: CGFloat) {
        
        self.header_height = viewHeight + self.viewModel.tableHeaderViewModel.headerExtensionHeight
        
        self.headerHeight_modified()
        
    }
    
    
}
